# 用户接口（注册、获取信息）
from fastapi import APIRouter, HTTPException, Depends
from fastapi.security import OAuth2PasswordRequestForm

from models.user import User
from models.role import Role
from schemas.user import UserCreate, UserOut
from core.security import has_password
from auth.auths import authenticate_user, create_token_response
from auth.deps import get_current_user,require_role


router = APIRouter(prefix="/users", tags=["用户"])


@router.post("/register", response_model=UserOut)
async def register(user: UserCreate):
    # if await User.get_or_none(username=user.username):
    #     raise HTTPException(status_code=404, detail="用户名已存在")
    # user_obj = await User.create(
    #     username = user.username,
    #     has_password = has_password(user.password)
    # )
    # return user_obj
    default_role = await Role.get_or_create(name="user")    # 默认角色
    hashed_pwd = has_password(user.password)
    role_obj, created = await Role.get_or_create(name="user")
    new_user = await User.create(
        username = user.username,
        hashed_password = hashed_pwd,
        role = role_obj
    )
    return new_user


@router.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = await authenticate_user(form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=401, detail="用户名或密码错误")
    return create_token_response(user.username)


@router.get("/me", response_model=UserOut)
async def get_me(current_user=Depends(get_current_user)):
    return current_user


@router.get("/admin-only")
async def admin_route(current_user=Depends(require_role(["admin"]))):
    return {"msg": f"欢迎管理员 {current_user.username}"}


@router.get("/user")
async def user_route(current_user=Depends(require_role(["user", "admin"]))):
    return {"msg": f"欢迎用户 {current_user.username}"}